/* 拦截fetch发出的请求
 * 数据模板文档:http://mockjs.com/
 *
 *
 */

import Mock from 'mockjs';
let Rules = [];
Mock._mock = Mock.mock;
Mock.mock = function(...argv) {
  if(argv.length>=2){
    argv[0] = typeof argv[0] === 'string'? new RegExp(argv[0]) : argv[0];
    Rules.push(argv);
    if(process && process.env.NODE_ENV!=='production'){
      if(argv[0].test('hot-update')){
        console.warn('[mock警告!] 规则: '+argv[0].toString()+' 会导致webpack热加载失效');
        return false;
      }

    }
  }
  return Mock._mock.apply(Mock, argv);
};


if (typeof window !== 'object' || typeof window.fetch !== 'function') {
  console.error('@当前浏览器环境不支持fetch@\n' + (window ? window.navigator.userAgent : ''));
} else {
  const STYLE = (function() {
    const BG = 'background:#222;';
    const FS = 'font-size:16px;';
    return [
      `color:#f2f2f2;${FS}${BG}`,
      `color:#CC99FF;${FS}${BG}font-weight:bold;`,
      `color:#f93;${FS}${BG}font-weight:bold;`,
      `color:#33CCFF;${FS}${BG}font-weight:bold;`,
      `color:#33FF66;${FS}${BG}font-weight:bold;`
    ];
  }());
  let orinin_fetch = window.fetch;
  let intercept= false;//是否拦截
  let outputLog = true; //是否在控制台中打印拦截日志
  const new_fetch = function(url = '', opt = {}) {
    if(!intercept){
      return orinin_fetch(url,opt);
    }
    let startNum = performance.now();
    for (let i in Rules) {
      let item = Rules[i];
      let reg = item[0];

      if (reg.test(url)) {
        let delay = parseInt(Math.random() * 1900) + 100;
        let data;
        let methodType = opt.method ? opt.method.toUpperCase() : 'GET';//当前fetch的请求方法
        if(item.length<=2){
          data = item[1];
        }else{
          if(typeof item[1]==='string'){//第二个参数是字符串时 判断请求方法是否匹配
            if(item[1].toUpperCase()=== methodType){
              data = item[2];
              if(typeof item[3]==='object'&&item[3].delay){//该拦截规则设置了特定的延时时间
                delay = item[3].delay;
              }
            }else{
              continue;//不匹配跳过后面操作
            }
          }else{
            if(typeof item[2]==='object'&&item[2].delay){
              delay = item[2].delay;
              data = item[1];
            }else{
              continue;//不匹配跳过后面操作
            }
          }
        }

        data = typeof data === 'function' ? data({...opt,url},url) : Mock.mock(data);
        delay = parseInt(typeof delay === 'function' ? delay({...opt,url},url) : delay);
        let ResOpt = {
          statusText: 'data from mock.js,cost ' + delay + ' ms.',
          headers: {
            'x-mock': 'true',
            'x-cost-time': delay + ' ms'
          }
        };//拦截数据时构造Response的额外选项
        let result = new Promise(function(resolve, reject) {
          setTimeout(function() {
            if(data instanceof Error){//模拟抛出错误
              reject(data);
            }else if(data instanceof Response){//模拟返回自定义响应头
              resolve(data);
            }else{
              resolve(new Response(typeof data === 'string'? data : JSON.stringify(data), ResOpt));
            }
          }, delay);
        });
        if (outputLog) {
          console.groupCollapsed('%c\u{1F680}mock拦截了一个fetch请求%c(点击展开详情)', 'font-size:17px;color:#f90;', 'font-size:12px;color:#CC3399;');
          let run_cost = (performance.now() - startNum).toFixed(2);
          console.info(`%c请求method：%c${methodType}%c ,url：%c${url}%c ,匹配第${+i+1}个规则 Regex：%c${reg.toString()}%c ,预计耗时：%c${delay} + ${run_cost} = ${delay+(+run_cost)}%c ms `, ...[
            STYLE[0],
            STYLE[2],
            STYLE[0],
            STYLE[1],
            STYLE[0],
            STYLE[4],
            STYLE[0],
            STYLE[3],
            STYLE[0]
          ]);
          console.info('mock返回的数据：', data);
          console.log('');
          console.groupEnd();
        }
        return result;
      }
    }

    return orinin_fetch(url, opt);
  };
  new_fetch.getRules = function() {
    return Rules;
  };
  new_fetch.getMock = function() {
    return Mock;
  };
  new_fetch.intercept=function(check){
    if(typeof check==='undefined'){
      return intercept;
    }else{
      intercept = !!check;
      console.warn(`${intercept?'启用':'禁用'}fetch拦截成功`);
    }
  };
  new_fetch.outputLog=function(check){
    if(typeof check==='undefined'){
      return outputLog;
    }else{
      outputLog = !!check;
      console.warn(`${outputLog?'启用':'禁用'}fetch拦截日志成功`);
    }
  };
  if(location.search.match(/[?&]not?_?intercept/)){//通过URL设置禁用
    new_fetch.intercept(false);
  }else if(location.search.match(/[?&]intercept/)){
    new_fetch.intercept(true);
  }
  window.fetch = new_fetch;
}
export default Mock;
